package testdemo;
//图片理解
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.image.Image2TextResponse;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Base64;
import java.util.Scanner;

public class demo4 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        // 直接在代码中设置访问密钥和密钥
        String accessKey = "ALTAKtcDh0nQtP40NgZUAmDA4K";
        String secretKey = "57a949833c7b408a81e06959785d90cf";

        // 创建 Qianfan 实例
        Qianfan qianfan = new Qianfan(accessKey, secretKey);
        System.out.println("请输入图片链接");
        String IMA=scanner.nextLine();
        // 使用图片URL
        String imageUrl = IMA;
        // 将图片URL转换为Base64编码
        String base64Image = convertImageToBase64(imageUrl);

        // 调试输出Base64编码后的数据长度
        if (base64Image != null) {
            System.out.println("Base64 Image Length: " + base64Image.length());
        } else {
            System.out.println("Failed to convert image to Base64.");
            return;
        }

        // 调用 API 将图片转文字
        try {
            Image2TextResponse response = qianfan.image2Text()
                    .image(base64Image)  // 使用 base64 编码后的图片数据
                    .prompt("introduce the picture")
                    .execute();
            System.out.println(response.getResult());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String convertImageToBase64(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            InputStream is = url.openStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            is.close();
            byte[] imageBytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
